from django.shortcuts import render, HttpResponse, HttpResponseRedirect

# 视图函数的语法: 第一个参数都是request
# 都要返回一个HttpResponse对象 或者 HttpResponse的子类
import os
import json
from newlife.settings import BASE_DIR
# from .utils.demo2 import Teacher, Student
from django.views.decorators.csrf import csrf_exempt, csrf_protect


def downloadfile(request, filename):
    # filedir = os.path.join(BASE_DIR, 'static', 'pic')
    filedir = os.path.join(r"E:\ai2107视频\sp")

    file_abspath = os.path.join(filedir, filename)

    file = open(file_abspath, "rb")
    response = HttpResponse(file)
    response['Content-Type'] = 'application/octet-stream'
    response['Content-Disposition'] = 'attachment;filename="{}"'.format(filename)
    return response


# content 内容
# context

def downfile(request):
    # filedir = os.path.join(BASE_DIR, 'static', 'pic')
    filedir = os.path.join(r"E:\ai2107视频\sp")

    filenames = os.listdir(filedir)

    return render(request, 'filelist.html', {"filenames": filenames})


# Create your views here.
def myhello(request):
    return HttpResponse("我自定义的界面xxxxx")


def index(request):
    print('xxxxxxxxxxxx')
    return render(request, 'basetem/index.html')


def index1(request):
    # return render(request, 'index1.html',context={"name":"张三"})  # content
    return render(request, 'index1.html', {"name": "张三"})


def index2(request):
    # return render(request, 'index2.html', {"list1": [x for x in range(1,6)]})
    return render(request, 'index2.html', {"list1": ["玄幻", "悬疑", "言情", "修仙"]})


def index_dict(request):
    return render(request, 'index_dict.html', {"person": {'name': "rose", "age": 18, "belong": "贵族"}})


# def index_obj(request):
#     t1 = Teacher(name="卡卡西")
#     t2 = Teacher(name="凯")
#
#     s1 = Student(name="鸣人", age=7, teacher=t1)
#     s2 = Student(name="小李", age=8, teacher=t2)
#
#     list_s = [s1, s2]
#     return render(request, "index_obj3.html", {"list_s": list_s})


# http://127.0.0.1:8000/school/geturlinfo/?wd=java&id=2
def geturlinfo(request):
    """
    获取url 中参数的方法
    :param request:
    :return:
    """
    # 获取通过get请求传过来的参数wd
    wd = request.GET.get("wd")
    id = request.GET.get("id")
    return HttpResponse("wd:{},id:{}".format(wd, id))


def geturlpathinfo(request, blogid):
    """
    获取url中路径中的 变量
    :param request:
    :param blogid: 路径中的参数
    :return:
    """
    return HttpResponse("blogid:{}".format(blogid))


def csdn(request, username, blogid):
    """
    获取url
    中路径信息
    :param
    request:
    :return:
    """
    return HttpResponse("username:{},blogid:{}".format(username, blogid))


def tespath(request, mypath):
    """
    获取url
    中路径信息
    path
    类型
    :param
    request:
    :return:
    """
    return HttpResponse("mypath:{}".format(mypath))


def book(request, bookid):
    return HttpResponse("{}".format(bookid))


def quesioneight(request, lantype, version):
    return HttpResponse("{},{}".format(lantype, version))


def myform(request):
    return render(request, 'myform.html')


# def myform2(request):
#     name = request.GET.get("name")
#     password = request.GET.get("password")
#     return HttpResponse("myform2,{},{}".format(name, password))
def myform2(request):
    name = request.POST.get("name")
    password = request.POST.get("password")
    return HttpResponse("myform2,{},{}".format(name, password))


def myform_post(request):
    return render(request, 'myform_post.html')


def myform_single(request):
    # 第一次请求
    # 如何判断请求方式
    if request.method == "GET":
        return render(request, 'myform_single.html')
    # 第二次请求 获取数据
    if request.method == "POST":
        name = request.POST.get("name")
        password = request.POST.get("password")
        return HttpResponse("{},{}".format(name, password))


def show(request):
    # print(request.get_raw_uri())
    # host = request.get_host()
    # print(host)

    if 'HTTP_X_FORWARDED_FOR' in request.META:  # 获取用户真实IP地址
        user_ip = request.META['HTTP_X_FORWARDED_FOR']
    else:
        user_ip = request.META['REMOTE_ADDR']
    print(user_ip)
    # print(dir(request.META))
    # print(request.META)
    # print(request.META.keys)
    response = HttpResponse("你的地址是:{}".format(user_ip))
    # response["custom"] = "自定义响应头"
    # response["Content-Type"] = "image/png"
    response["Content-Type"] = "application/json"
    return response


def upfile(request):
    if request.method == "GET":
        return render(request, "upfile.html")

    if request.method == "POST":
        file = request.FILES.get("file")
        print(file)
        print(type(file))
        with open('kk.jpg', 'wb') as f:
            for chunk in file.chunks():
                f.write(chunk)
        return HttpResponse("kkk")


# def jsontest(request):
#     result = [x for x in range(1, 5)]
#     return HttpResponse(json.dumps(result), content_type="application/json")
def jsontest(request):
    result = [x for x in range(1, 5)]
    response = HttpResponse(json.dumps(result))
    response["Content-Type"] = "application/json"
    return response


from django.shortcuts import redirect, reverse, resolve_url, HttpResponse
from django.urls import reverse


# def testredirect(request):
#     return redirect('school2:index')


# quesioneight(request, lantype, version):

def testredirect(request):
    # path = reverse('index')
    # path = reverse('quesioneight',kwargs={'lantype':'kk','version':33})
    # path = reverse('quesioneight',args=["kk",22])
    # path = reverse('quesioneight', args=["kk", 22])
    # path = resolve_url('index')
    # path = resolve_url('quesioneight', "kk", 22)
    path = resolve_url('quesioneight', lantype='zh', version=2.2)
    print(path)
    print(type(path))
    # return redirect(path)
    # return redirect('quesioneight','kk',33)
    # return redirect('quesioneight',lantype='kk',version=32)
    return redirect("https://baidu.com/s{}".format('?wd=python'))


from django.template.defaultfilters import add

from django.core.handlers.wsgi import WSGIRequest


def question2(request):
    if request.method == "GET":
        return render(request, 'question2.html')

    if request.method == "POST":
        username = request.POST.get("username", '未知')
        age = request.POST.get("age", '未知')
        phone = request.POST.get("phone", '未知')

        icon = request.FILES.get('icon')
        print(icon.name)  # 获取上传图片的原始名称
        with open("{}.jpg".format(username), 'wb') as f:
            for chunk in icon.chunks():  # 分块读取,防止文件过大,弄崩内存
                f.write(chunk)

        if 'HTTP_X_FORWARDED_FOR' in request.META:  # 获取用户真实IP地址
            user_ip = request.META['HTTP_X_FORWARDED_FOR']
        else:
            user_ip = request.META['REMOTE_ADDR']

        return HttpResponse("name:{},age:{},phone:{},ip:{}".format(username, age, phone, user_ip))


from django.shortcuts import redirect

from django.urls import reverse


# def quesioneight(request, lantype, version):
def testfun(request):  # function
    # print(type(request))
    # return redirect('index2') # 通过view name跳转
    # return redirect('/school/index2') # 通过硬编码 绝对路径 跳转
    # return redirect('book', 33)  # 有参数咋办
    # return redirect('quesioneight', 'zh', 3.3)  # 有参数咋办
    # return redirect('quesioneight', lantype='zh',version=3.3)  # 有参数咋办
    # return redirect('baidu.com')  # 识别为相对地址  本机的
    # return redirect('www.baidu.com')  # 跳转 百度
    # return redirect('http://www.baidu.com')  # 跳转 百度
    # return redirect('http://baidu.com')  # 跳转 百度
    # [命名空间/appname]:路由名字
    # reverse()  # 根据函数名获取到 url的路径   路由反向解析
    # resolve_url()
    # return redirect('school2:index')  # 跳转 到指定应用 下的 指定路由
    # indexpath = reverse("index")  # 路由反向解析

    # path = reverse("book",args=[1,])  # 路由反向解析
    # path = reverse("quesioneight",args=['zh',3.4])  # 路由反向解析
    # path = reverse("book", kwargs={'bookid': 3})  # 路由反向解析
    # path = reverse("quesioneight", kwargs={'lantype': 'zh', 'version': 3.4})  # 路由反向解析
    # path = resolve_url('index')
    # path = resolve_url('book', 5)
    # path = resolve_url('quesioneight','zh',3.4)
    # path = resolve_url('book',bookid=6)
    # path = resolve_url('quesioneight', lantype='en', version=77)
    # path = resolve_url('school2:index')
    path = reverse('school2:index')
    print(path)
    return redirect(path)


# def quesioneight(request, lantype, version):
# 根据函数名获取到 url的路径   路由反向解析  reverse  resolve_url

def tesurl(request):
    return render(request, 'tesurl.html')


def testtem(request):
    # return render(request, 'testtem.html',{'list1':['苹果','桃子']})
    # return render(request, 'testtem.html',{'list1':['苹果','桃子']})
    return render(request, 'testtem1.html')


from .models import Student
from .models import Course


def student(request):
    # 学生的信息包括 name, 班级名称classname, 身份证号cardid,手机号码phone.
    if request.method == "GET":
        return render(request, 'student.html')

    if request.method == "POST":
        name = request.POST.get('name', '未知')
        classname = request.POST.get('classname', '未知')
        cardid = request.POST.get('cardid', '未知')
        phone = request.POST.get('phone', '未知')

        s = Student(name=name, classname=classname, cardid=cardid, phone=phone)
        s.save()
        # todo 通过模型存数据库
        return HttpResponse("插入成功!")


from django.db import connection


def testrelation(request):
    # c = Course(name='python基础', level='0')
    # c.save()
    #
    # s = Student(name="张三", classname='2100A', cardid='12344', phone=1223, course_id=6)
    # s = Student(name="李四", classname='2100A', cardid='12344', phone=1223, course_id=6)
    # s.save()
    # 反向查询 relate_name
    # 删除操作 演示

    # Student.objects.get(name='张三').delete()
    # Course.objects.get(id=6).delete()

    # 正向查询  根据从表查主表的数据
    # 李四 学的 课程名字 是什么
    # result  = Student.objects.get(name='李四').course.name
    # print(result)
    # 反向查询   学python基础的课程 学生都有哪些
    # django.db.models.fields.related_descriptors.create_reverse_many_to_one_manager. < locals >.RelatedManager
    # ss = Course.objects.get(id=7).student_set.all()
    # 从表的模型_set.all()
    ss = Course.objects.get(id=7).student.all()
    # ss = Course.objects.filter(id=7).student.all()  #xxx_set是对象才有的,queryset没有
    print(ss)
    # 如何查看 代码执行的 sql语句
    # 对于 queryset , query属性可以看到这个queryset是怎么来的
    # print(type(ss))
    # print(ss.query)

    # for s in ss:
    #     print(s.name)
    #     print(s.phone)
    #     print(s.cardid)
    # ------------------执行原生sql--------------------
    # res = Student.objects.raw("select * from shool_course")
    # print(type(res))
    # for student in res:
    #     print(student)

    # cursor = connection.cursor()
    # cursor.execute('select * from shool_student')
    # ret = cursor.fetchall()
    # print(type(ret))
    # print(ret)

    return HttpResponse('ok----testrelation--11111--')


from .utils.demo4 import Group


def paging(request):
    # 获取到  分页对象
    course = Course.objects.all()
    print(len(course))
    # 整体数据, 每一页大小
    g = Group(course, 3)

    # print(g.max_group_count())
    # print(g.obj_list)
    # print(g.per_page)
    # print(g.get_group(2))
    x = request.GET.get("page", '1')
    try:
        x = int(x)
        if x < 0:
            x = 1
    except Exception as e:
        x = 1

    pagex = g.get_group(x)
    print(x)
    return render(request, 'paging.html', {"pagex": pagex})


from django.core.paginator import Paginator


# Paginator Group

def pagedjango(request):
    course = Course.objects.all()
    paginator = Paginator(course, 2)
    # 获取 url 传过来的page 值
    x = request.GET.get("page", '1')
    try:
        x = int(x)
        if x < 0:
            x = 1
    except Exception as e:
        x = 1

    pagex = paginator.get_page(x)
    pagex = pagex.object_list

    return render(request, 'paging.html', {"pagex": pagex})


from django.db import connection


def queryobj(request):
    # 展示搜索界面
    if request.method == "GET":
        return render(request, 'queryobj.html')

    # 处理搜索逻辑
    if request.method == "POST":
        wd = request.POST.get("wd")
        # 方式1
        courses = Course.objects.filter(name__contains=wd).all()
        # 方式2 原生
        sql = "select * from shool_course where name like '%{}%'".format(wd)
        print(sql)
        # res = Course.objects.raw(sql)
        # manager
        # res = Student.objects.raw(sql)
        # print(res)
        # print(type(res))  # <class 'django.db.models.query.RawQuerySet'>  不可打印
        # 真-原生
        cursor = connection.cursor()
        cursor.execute(sql)
        result = cursor.fetchall()
        print(type(result[0]))
        print(result)
        return render(request, 'result.html', {"courses": courses})

# from django.db.models.query import RawQuerySet
